import urllib.request
import json
import os



# 根据所给英雄数据地址获取英雄数据
def get_hreo_data(data_url):
    hero_json = []
    response = urllib.request.urlopen(data_url)
    hero_json = json.loads(response.read())
    return hero_json


# 爬取英雄名称和皮肤名称到文件中
def crawl(hero_json, save_file):
    if not hero_json:
        print('请先获取英雄数据')
        return
    if not save_file:
        save_file = 'hero.txt'
    with open(save_file, 'w', encoding='utf-8') as file:
        for hero in hero_json:
            try:
                message = '英雄：%s,皮肤：%s\n' % (hero['cname'], hero['skin_name'].split('|'))
                file.write(message)
            except Exception:
                message = '英雄：%s,皮肤：%s\n' % (hero['cname'], hero['title'])
                file.write(message)
        print('保存成功！')


# 爬取英雄皮肤图片到文件夹中
def heroskin(hero_json, save_path):
    if not hero_json:
        print('请先获取英雄数据')
        return
    if not save_path:
        save_path = 'heroskinimg\\'
    save_dir =  save_path #英雄皮肤图片保存路径，会在项目根目录下创建
    if not os.path.exists(save_dir): # 如果文件夹不存在就创建
        os.mkdir(save_dir)
        print('文件创建成功！')
    for hero in hero_json:
        try:
            skin_name = hero['skin_name'].split('|')
            for i in range(len(skin_name)):
                # 构建图片名称
                save_file_name = save_dir + str(hero['ename']) + '-' + hero['cname'] + '-' + skin_name[i] + '.jpg'
                # 根据皮肤图片规律拼接完整皮肤路径
                skin_url = 'http://game.gtimg.cn/images/yxzj/img201606/skin/hero-info/' + \
                           str(hero['ename']) + '/' + str(hero['ename']) + \
                           '-bigskin-' + str(i + 1) + '.jpg'
                if not os.path.exists(save_file_name):
                    # 抓取皮肤图片
                    urllib.request.urlretrieve(skin_url, save_file_name)
        except:
            save_file_name = save_dir + str(hero['ename']) + '-' + hero['cname'] + '-' + hero['title'] + '.jpg'
            skin_url = 'http://game.gtimg.cn/images/yxzj/img201606/skin/hero-info/' + \
                       str(hero['ename']) + '/' + str(hero['ename']) + \
                       '-bigskin-' + str(1) + '.jpg'
            if not os.path.exists(save_file_name):
                urllib.request.urlretrieve(skin_url, save_file_name)


